package com.example.demo.aop;

import com.example.demo.entity.Log;
import com.example.demo.mapper.LogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogMapper logMapper;

    private ThreadLocal<Date> startTime = new ThreadLocal<>();

    @Pointcut("(@within(com.example.demo.aop.Logger) || @annotation(com.example.demo.aop.Logger))")
    public void addLogPointCut(){
    }

    @Before("addLogPointCut()")
    public void setStartTime(JoinPoint joinPoint){
        startTime.set(new Date());
    }

    @AfterReturning("addLogPointCut())")
    public void addLog(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Logger logger = method.getAnnotation(Logger.class);

        Log log = new Log();
        log.setDescription(logger.description());
        log.setUrl(logger.url());
        log.setStartTime( startTime.get());
        log.setEndTime(new Date());
        log.setDataSheer(logger.dataSheer());

        // 记录日志
        int res = logMapper.insertLog(log);
        if (res == 1){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
//        System.out.printf("成功-描述:%s 网址:%s 开始时间:%s 结束时间:%s 数据表:%s%n",
//                logger.description(),
//                logger.url(),
//                startTime.get(),
//                new Date(),
//                logger.dataSheer()
//        );
        startTime.remove();
    }


}
